<template>
  <PageModal
    :show="show"
    :page-style="pageStyle"
    :footer-size="footerSize"
    :footer-style="footerStyle"
    @back="closeModal"
  >
    <template #header>
      <view class="custom-header">
        <image
          v-if="control.store._datasource.brand"
          class="sui-icon"
          :class="{
            'sui-Bos-icon': control.store._datasource.brand === 'BOSCH',
          }"
          mode="heightFix"
          :src="`/pages/appliance/static/SUI_${control.store._datasource.brand}.png`"
        />
        <text>{{ $t('Dishwasher.Sui.MachinePanelProgramManagement.Title.Text') }}</text>
      </view>
    </template>

    <view v-if="!adjustParameterVisible" class="favorite-box">
      <view class="tabs-box">
        <view class="tabs-title-box">
          <view
            class="tabs-title"
            v-for="(favorite, index) in favoriteProgramsSui"
            :key="index"
            :class="{ active: index === favoriteIndex }"
            @click="changeFavorite(index)"
          >
            <text>{{
              (favorite.value && favorite.value[0]?.name) || $t('Dishwasher.Sui.ProgramList.NoneProgram.Text')
            }}</text>
          </view>
        </view>
        <view class="tabx-line-box">
          <view class="tabs-line" :class="{ active: favoriteIndex === 0 }"></view>
          <view class="tabs-line" :class="{ active: favoriteIndex === 1 }"></view>
        </view>
      </view>
      <view class="programs-box">
        <view class="title-box">
          <view class="title">{{ $t('Dishwasher.Sui.MachinePanelProgramManagement.Programs.Title.Text') }}</view>
          <view class="adjust" :class="{ disabled: adjustDisabled }" @click="adjustParameter(true)">{{
            $t('Dishwasher.Sui.MachinePanelProgramManagement.Programs.Button.Text')
          }}</view>
        </view>
        <ProgramList
          :programs="programs"
          :active-key="activeProgramKey"
          :active-tips="activeProgramRemaining"
          @select="onProgramSelect"
        ></ProgramList>
      </view>
    </view>

    <AdjustParameterModal v-model:show="adjustParameterVisible" custom-footer :control="control" back-text="选择程序">
      <template #footer>
        <view class="btn-box">
          <view class="btn cancel" @click="adjustParameter(false)">{{
            $t('Dishwasher.Sui.MachinePanelProgramManagement.Options.Cancel.Button.Text')
          }}</view>
          <view class="btn save" @click="save">{{
            $t('Dishwasher.Sui.MachinePanelProgramManagement.Options.Save.Button.Text')
          }}</view>
        </view>
      </template>
    </AdjustParameterModal>

    <template #footer>
      <view class="btn-box">
        <view class="btn cancel" @click="closeModal">{{
          $t('Dishwasher.Sui.MachinePanelProgramManagement.Programs.Cancel.Button.Text')
        }}</view>
        <view class="btn save" :class="{ disabled: adjustDisabled }" @click="save">{{
          $t('Dishwasher.Sui.MachinePanelProgramManagement.Programs.Save.Button.Text')
        }}</view>
      </view>
    </template>
  </PageModal>
</template>

<script setup lang="ts">
import ProgramList from '@/pages/appliance/components/programList.vue'
import AdjustParameterModal from '../../view/adjustParameterModal.vue'

import type { CSSProperties } from 'vue'
import { footerStyle, footerSize } from '@/layout/appliance/style'
import type { ApplianceProgram } from '@/types/appliance'
import type { DishwasherController } from '@/controller/Dishwasher/definition'
import { setSetting, type ApplianceDetailOption } from '@/api/appliance'
import {
  BSH_COMMOM_PROGRAM_FAVORITE_001,
  BSH_COMMOM_PROGRAM_FAVORITE_002,
  DISHWASHER_SILTENT_ON_DEMAND,
  START_IN_RELATIVE,
} from '@/constants/Command'
import { actionDebounce } from '@/utils/mpHelper'
import { useI18n } from 'vue-i18n'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'
import PageModal from '@/common/pageModal.vue'

export type FavoriteProgramsType = {
  key: string
  value: FavoriteProgramsValueType[]
}
export type FavoriteProgramsValueType = {
  key: string
  name: string
  options: FavoriteProgramsValueOptionsType[]
}
export type FavoriteProgramsValueOptionsType = {
  key: string
  name: string
  value: boolean
}
export type SettingFavoritePrograms = {
  key: string
  value: FavoriteProgramsValueType[]
}
export type FavoriteOptType = {
  key: string
  name: string
  value: FavoriteOptValueType[]
}
export type FavoriteOptValueType = {
  key: string
  name: string
  value: number
  unit?: string
}

const pageStyle: CSSProperties = {
  backgroundColor: '#ffffff',
}
const i18n = useI18n()

const props = defineProps<{
  show: boolean
  control: DishwasherController.Control
}>()

const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
  (e: 'close'): void
}>()

function closeModal() {
  adjustParameterVisible.value = false
  emit('update:show', false)
  emit('close')
}

const programs = computed(() => getNoneFavoritePrograms(props.control.store.allPrograms || []))
const activeProgramKey = computed(() => props.control.store.currentProgramKey)
const activeProgramRemaining = computed(() => props.control.store.programRemainingText)
const favoriteProgramsSui = computed(() => props.control.store.favoriteProgramsSui)
const currentOptions = computed(() => props.control.store.detail?.option || [])
const favoriteIndex = ref(0)
const adjustParameterVisible = ref(false)
const adjustDisabled = computed(() =>
  ['', BSH_COMMOM_PROGRAM_FAVORITE_001, BSH_COMMOM_PROGRAM_FAVORITE_002].includes(activeProgramKey.value)
)

watch(
  () => props.show,
  (show) => {
    if (show) {
      // 优先显示未设置的程序，如果都未设置，显示左，如果都有设置默认选中当前选中的程序
      let nullIndex =
        favoriteProgramsSui.value &&
        favoriteProgramsSui.value.findIndex(
          (favorite: FavoriteProgramsType) => !favorite.value[0] || !favorite.value[0].name
        )
      if (nullIndex !== -1) {
        favoriteIndex.value = nullIndex
      } else {
        favoriteIndex.value = activeProgramKey.value.indexOf('002') !== -1 ? 1 : 0
      }
    }
  }
)

function getNoneFavoritePrograms(programs: ApplianceProgram.Scope[]) {
  if (!programs || programs.length === 0) return []
  return programs.filter((program) => {
    return ![BSH_COMMOM_PROGRAM_FAVORITE_001, BSH_COMMOM_PROGRAM_FAVORITE_002].includes(program.key)
  })
}

/**
 * 切换tab栏
 * @param index
 */
function changeFavorite(index: number) {
  favoriteIndex.value = index
}
/**
 * selected program
 * @param program
 */
async function onProgramSelect(program: ApplianceProgram.Scope) {
  await props.control.store.setCurrentProgram(program)
}
/**
 * 保存
 */
const save = actionDebounce({
  loadingText: i18n.t('APP.Common.Saving.Text'),
  call: async () => {
    let submitParams: FavoriteOptType[] = [
      {
        key: activeProgramKey.value,
        name: programs.value.find((item) => item.key === activeProgramKey.value)?.name as string,
        value: [
          {
            key: 'BSH.Common.Option.StartInRelative',
            value: 0,
            unit: 'seconds',
            name: '开始时间',
          },
        ],
      },
    ]
    let newOptions = clearOptions(currentOptions.value)
    newOptions.forEach((item) => {
      submitParams[0].value.push({
        key: item.key as string,
        value: item.value as number,
        name: item.name as string,
      })
    })

    let res: any = null
    try {
      res = await setSetting(
        props.control.store._datasource.haId,
        favoriteProgramsSui.value[favoriteIndex.value].key,
        submitParams
      )
    } catch (error) {
      res = error
    } finally {
      if (res && res.code === 0) {
        uni.showToast({
          title: i18n.t('APP.Common.SaveSucess.Text'),
          icon: 'success',
        })
        closeModal()
      }
      // 埋点逻辑
      if (res === undefined) res = {}
      safeTrack(() => {
        type TackData = {
          program_name: string
          program_key: string
          [x: string]: unknown
        }
        let trackData: TackData = {
          program_name: '',
          program_key: '',
          successOrNot: 'code' in res ? res.code == 0 : false,
          error_code: 'code' in res ? res.code : -1,
          response_msg: 'msg' in res ? res.msg : 'unknow',
        }
        trackData.program_name = submitParams[0].name
        trackData.program_key = submitParams[0].key

        trackData.favorite_value_obj = JSON.stringify({ ...submitParams[0].value })
        trackEvent('favorite_program', trackData, TrackType.ApplianceDetail, 'Appliance.SUI.AddFavorite.Save')
      })
    }
  },
})
/**
 * 显示调节参数
 */
function adjustParameter(value: boolean) {
  adjustParameterVisible.value = value
}
/**
 * 清楚options中多余数据
 * @param list
 */
function clearOptions(list: ApplianceDetailOption[]) {
  return list.filter((item) => ![START_IN_RELATIVE, DISHWASHER_SILTENT_ON_DEMAND].includes(item.key))
}
</script>
<style scoped lang="less">
.disabled {
  opacity: 0.4;
  pointer-events: none;
}
.custom-header {
  display: flex;
  align-items: center;
}
.sui-icon {
  height: 40rpx;
  margin-right: 16rpx;
}
.sui-Bos-icon {
  margin-right: 0;
}
.favorite-box {
  padding: 60rpx 0 0;
  .tabs-box {
    padding: 0 32rpx;
    .tabs-title-box {
      display: flex;
      margin-bottom: 24rpx;
      .tabs-title {
        width: 50%;
        text-align: center;
        font-weight: 500;
        font-size: 48rpx;
        color: var(--dark-color);
        opacity: 0.8;
      }
      .active {
        color: var(--primary-color);
        opacity: 1;
        font-weight: 600;
      }
    }
    .tabx-line-box {
      display: flex;
      width: 100%;
      height: 12rpx;
      background: #e9e9ed;
      border-radius: 16rpx;
      .tabs-line {
        width: 50%;
      }
      .active {
        width: 50%;
        border-radius: 16rpx;
        background-color: var(--primary-color);
      }
    }
  }
  .programs-box {
    margin-top: 48rpx;

    .title-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 32rpx;
      .title {
        font-weight: 600;
        font-size: 48rpx;
        color: var(--dark-color);
      }
      .adjust {
        font-weight: 600;
        font-size: 28rpx;
        color: var(--primary-color);
      }
    }
  }
}
.btn-box {
  display: flex;
  justify-content: space-around;
  align-items: center;
  font-weight: 600;
  font-size: 32rpx;
  line-height: 44rpx;
  .save {
    color: var(--primary-color);
  }
}
</style>
